<template>
  <div class="h-full flex flex-col text-#fff justify-center">
    <div class="h-50px leading-50px text-20px text-center px-20px" v-if="dataSources.length">
      {{ currentChatHistory?.title }}
    </div>
    <main class="overflow-hidden" :class="{ 'flex-1': dataSources.length }">
      <el-scrollbar ref="scrollRef">
        <div id="scroll-box" class="w-full max-w-screen-md m-auto">
          <div v-if="!dataSources.length" class="text-center p-20px">
            <div class="text-26px font-bold">我是智能助手，很高兴见到你</div>
            <div class="text-14px mt-10px">我可以帮你分析告警信息，快速定位故障位置</div>
          </div>
          <div v-else>
            <Message
              v-for="(item, index) of dataSources"
              :key="index"
              :date-time="item.dateTime"
              :text="item.text"
              :reasoning="item.reasoning"
              :inversion="item.inversion"
              :error="item.error"
              :loading="item.loading" />
          </div>
        </div>
      </el-scrollbar>
    </main>
    <!-- 输入框 -->
    <footer>
      <div class="py-20px max-w-screen-md m-auto">
        <div class="p-15px bg-#031935 rounded-24px">
          <div class="input-box">
            <el-input
              v-model="prompt"
              style="width: 100%"
              :autosize="{ minRows: 2, maxRows: 4 }"
              type="textarea"
              resize="none"
              placeholder="发送消息"
              @keypress="handleEnter" />
          </div>
          <div class="flex items-center justify-between">
            <div></div>
            <div class="flex items-center">
              <!-- <el-button :icon="Link" circle /> -->
              <el-button v-if="loading" type="primary" :icon="CloseBold" circle @click="handleStop" />
              <el-button v-else type="primary" :icon="Position" :disabled="!prompt" circle @click="handleSubmit" />
            </div>
          </div>
        </div>
      </div>
    </footer>
  </div>
</template>

<script setup lang="ts">
import {CloseBold, Position} from '@element-plus/icons-vue'
import Message from './components/Message/index.vue'
import {computed, nextTick, onMounted, onUnmounted, ref} from 'vue'
import {chatCompletions} from '@/api/chat'
import {useChat} from './hooks/useChat'
import {useScroll} from './hooks/useScroll'
import {useChatStore, useAuthStore} from '@/store'
import {useRoute} from 'vue-router'
import {useReadStream} from './hooks/useReadStream'
import {ss} from "@/utils/storage";

let controller = new AbortController()
const chatStore = useChatStore()
const route = useRoute()

// 会话方法
const { addChat, updateChat } = useChat()
const { scrollRef, scrollToBottom, scrollToBottomIfAtBottom } = useScroll()
const { handleStreamResponse } = useReadStream()
const { uuid } = route.params as { uuid: string }
// 输入框
const prompt = ref<string>('')
const loading = ref<boolean>(false)
// 对话信息
const dataSources = computed(() => chatStore.getChatByUuid(+uuid))
const currentChatHistory = computed(() => chatStore.getChatHistoryByCurrentActive)

// 是否开启多轮对话，开启后会带上之前的聊天信息
const usingContext = computed<boolean>(() => chatStore.usingContext)

const authStore = useAuthStore();

//解析参数信息
function handlerMessage() {
  try {
    if (dataSources && dataSources.value.length) {
      return;
    }
    const iframeSrc = window?.location?.href;
    console.log("handlerMessage",iframeSrc)
    if(iframeSrc) {
      const urlObj = new URL(iframeSrc);
      // 获取 hash 部分
      const hash = urlObj.hash; // => "#/chat?name=..."
      const hashQuery = hash.split('?')[1]; // => "name=....&pathName=..."
      const params = new URLSearchParams(hashQuery);
      let monitor_name = params.get('monitor_name');
      if (monitor_name && !prompt.value) {
        prompt.value = decodeURIComponent(monitor_name)
        // 确保DOM更新后提交
        nextTick(() => {
          handleSubmit()
        })
      }
    }
  } catch (error) {
    console.error('消息处理失败:', error)
  }finally {
    // const urlObj = new URL("http://198.87.103.134/chat/#/chat?name=ai&monitor_name=OCS%E7%B3%BB%E7%BB%9F500KV220kV%E6%B8%94%E9%98%B3%E5%8F%98%E7%94%B5%E7%AB%99_2#%E4%B8%BB%E5%8F%98220%E6%95%B0%E6%8D%AE%E4%B8%8D%E5%88%B7%E6%96%B0&pathName=/console/embed/outer/YWlA5pm66IO95Yqp5omL&accessToken=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkY2FjZmIxYWE3NDY0YjU1OTQ5MTA4MDdiYjg4N2QyZSIsInZlciI6IkRCMS4wIiwidXNlcl9uYW1lIjoiYXlvbmciLCJwcmkiOlsiQURNSU4iXSwibGFzdF9sb2dpbiI6MTc1MTI3NjUyOSwic2NvcGUiOlsiYWxsIl0sImlzcyI6Im5yZWMiLCJleHAiOjE3NTEzNjI5MjksImp0aSI6ImY4N2U3NzcyLTJiZGYtNDgwMi05YmJmLWU5MzE5ZWNmODNhNyIsImNsaWVudF9pZCI6ImZyb250ZW5kIn0.Qdv7SHZ8gEYeDwBO2GC6iFy-6ejKBrhrGFc2t9qr-pnyMKy-K5_3rsUql25JzQ0D0enYAlydp4FM-lNqW7NuVaYEXARFOkWOoequOmEhHa5UygVffN-MBR1rWEDHT85tM7Kizn4PuxU_vWVCaJNGVmdxJVpIY_QejodGpIOVjrI");
    // // 获取 hash 部分
    // const hash = urlObj.hash; // => "#/chat?name=..."
    // const hashQuery = hash.split('?')[1]; // => "name=....&pathName=..."
    // const params = new URLSearchParams(hashQuery);
    // let monitor_name = params.get('monitor_name');
    // if (monitor_name) {
    //   prompt.value = decodeURIComponent(monitor_name)
    //   // 确保DOM更新后提交
    //   nextTick(() => {
    //     handleSubmit()
    //   })
    // }
  }
}

// 输入框回车事件
function handleEnter(event: KeyboardEvent) {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    handleSubmit()
  }
}
function handleSubmit() {
  if (!+uuid || +uuid === 0) {
    chatStore.addHistory({
      conversationId: '',
      userId: authStore.getUser.sub,
      title: '新建会话',
      uuid: Date.now(),
      isEdit: false,
      visible: false,
    })
    ss.set('chatSubmitPrompt', prompt.value)
    return
  }
  onConversation()
}
async function onConversation() {
  let message = prompt.value
  if (loading.value) return
  if (!message || message.trim() === '') return
  // 流式输出信号
  controller = new AbortController()
  const conversationList = dataSources.value.filter(item => item.text).map(item => ({
    // role: item.inversion ? 'user' : 'assistant',
    query: item.text,
  } as Chat.ConversationMessage))
  // 添加用户消息到对话框
  await addChat(+uuid, {
    dateTime: new Date().toLocaleString(),
    text: message,
    inversion: true,
    error: false,
  })
  console.log("加载数据...");
  await new Promise(resolve => setTimeout(resolve, 500)); // 模拟网络请求延迟
  console.log("数据加载完成");
  scrollToBottom()
  loading.value = true
  prompt.value = ''
  // 添加AI初始对话 思考信息
  await addChat(+uuid, {
    dateTime: new Date().toLocaleString(),
    text: '',
    reasoning: '思考中...',
    loading: true,
    inversion: false,
    error: false,
  })
  scrollToBottom()
  // 开始发起请求
  try {
    const paramMsg = []
    if (usingContext.value && false) {
      // AI回复 是不是要把ai回复删掉
      paramMsg.push(...conversationList)
    }
    paramMsg.push({ query: message })
    const response: any = await chatCompletions(controller.signal, paramMsg, currentChatHistory?.value?.conversationId ?? '')
    await handleStreamResponse(response, (jsonData: any) => {
      console.log("jsonData",jsonData)
      const contentText = jsonData?.answer;
      const conversationId = jsonData?.conversation_id;
      if (currentChatHistory.value && !currentChatHistory.value?.conversationId) {
        const history = {
          ...currentChatHistory.value, // 保留其他属性
          conversationId              // 更新指定属性
        }
        chatStore.updateHistoryConversationId(history)
      }
      if (contentText) {
        updateChat(+uuid, dataSources.value.length - 1, {
          text: contentText ?? '',
          inversion: false,
          error: false,
          loading: true,
        })
        scrollToBottomIfAtBottom()
      }
      // 思考信息
      /*const reasoning = jsonData.choices[0].delta.reasoning_content
      if (reasoning) {
        updateChat(+uuid, dataSources.value.length - 1, {
          reasoning: reasoning ?? '',
          reasoningTime: new Date().toLocaleString(),
          inversion: false,
          error: false,
          loading: true,
        })
        scrollToBottomIfAtBottom()
      }*/
    })
    updateChat(+uuid, dataSources.value.length - 1, {
      inversion: false,
      error: false,
      loading: false,
    })
    loading.value = false
    console.log('Stream ended')
  } catch (error: any) {
    console.log(error)
    loading.value = false
    if (error instanceof DOMException && error.name === 'AbortError') {
      updateChat(+uuid, dataSources.value.length - 1, {
        text: '\n\n用户手动中断。',
        inversion: false,
        error: false,
        loading: false,
      })
    } else {
      updateChat(+uuid, dataSources.value.length - 1, {
        text: '\n\n服务器异常，请稍后再试。',
        inversion: false,
        error: true,
        loading: false,
      })
    }
  }
}
function handleStop() {
  if (loading.value) {
    controller.abort()
    loading.value = false
  }
}
onMounted(() => {
  console.log('onMounted', prompt.value)
  //加载数据
  chatStore.loadChatData()

  if (!route.params.uuid) {
    chatStore.active = 1002
  }
  const promptValue = ss.get('chatSubmitPrompt')
  if (promptValue) {
    prompt.value = promptValue
    ss.set('chatSubmitPrompt', '')
    onConversation()
  }
  // 如果是跳转过程来并且有参数的，解析并发送消息
  handlerMessage()
  scrollToBottom()
})
onUnmounted(() => {
  console.log('onUnmounted')
  if (loading.value) controller.abort()
})
</script>

<style scoped lang="scss">
.input-box {
  :deep(.el-textarea) {
    .el-textarea__inner {
      background-color: transparent;
      color: #fff;
      box-shadow: none;
      padding: 0;
      font-size: 16px;
    }
  }
}
</style>
